package models

import (
	"hytx_media/pkg/util"
	"time"
)

type Message struct {
	ID        uint `gorm:"primary_key" json:"id"`
	From      uint
	To        uint
	Type      uint
	Title     string
	Target    uint
	IsRead    uint
	CreatedAt time.Time
	UpdatedAt time.Time
}

type MessageResult struct {
	ID        int       `json:"id"`
	Title     string    `json:"title"`
	IsRead    int       `json:"is_read"`
	Type int 	`json:"type"`
	CreatedAt time.Time `json:"created_at"`
}

type CommentMessageResult struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	ArticleId int       `json:"article_id"`
	Title     string    `json:"title"`
	Content   string    `json:"content"`
	IsRead    int       `json:"is_read"`
	CreatedAt time.Time `json:"created_at"`
	HeadPortrait string `json:"head_portrait"`
}

type FollowMessageResult struct {
	ID           int       `json:"id"`
	Name         string    `json:"name"`
	HeadPortrait string    `json:"avatar"`
	IsRead       int       `json:"is_read"`
	CreatedAt    time.Time `json:"created_at"`
}

type FAndSMessageResult struct {
	FollowMessageResult
	Title string 	`json:"title" `
}

func (Message) TableName() string {
	return "media_message"
}

/**
	获取最后一次已读的系统通知
 */
func GetLastReadSysNotice(userId int) (*Message, error) {
	var msg Message
	err := DB.Where("`to` = ? AND `type` < 2 AND `is_read` = 1", userId).Last(&msg).Error
	if err != nil {
		return nil, err
	}

	return &msg, nil
}

/**
	获取大于id的消息，就是新系统公告
 */
func GetLastSysNoticeCount(id uint) (int, error) {
	var count int
	err := DB.Model(&Message{}).Where("`id` > ? AND `type` < 2 AND `is_read` = 0", id).Count(&count).Error
	if err != nil {
		return 0, err
	}

	return count, nil
}

/**
	未读消息
 */
func GetMessageCount(userId int, t int) (int, error) {
	var count int
	err := DB.Model(&Message{}).Where("`to` = ? AND `type` = ? AND `is_read` = 0", userId, t).Count(&count).Error
	if err != nil {
		return 0, err
	}

	return count, err
}

func GetNoticeList(userId int, page int, limit int) ([]*MessageResult, *util.Paginate, error) {
	var result []*MessageResult
	var count int
	DB.Model(&Message{}).Where("`type` IN (0, 1, 2) AND `to` IN (0, ?)", userId).Count(&count)
	paginate := &util.Paginate{Page: page, Limit: limit, Count: count}
	if count <= 0 {
		return result, paginate, nil
	}
	err := DB.Model(&Message{}).Select("media_message.id,media_message.type, mc.title, is_read, media_message.created_at").Joins("left join media_message_content mc on mc.msg_id=media_message.id").Where("media_message.`type` IN (0, 1, 2) AND media_message.`to` IN (0, ?)", userId).Order("media_message.created_at desc").Offset(paginate.Offset()).Limit(paginate.Limit).Scan(&result).Error
	if err != nil {
		return nil, nil, err
	}
	var ids []int
	for _, i := range result{
		ids = append(ids, i.ID)
	}
	readMessage(ids)
	return result, paginate, nil
}
/**
	获取评论消息
 */
func GetCommentMessageList(userId int, page int, limit int) ([]*CommentMessageResult, *util.Paginate, error) {
	var result []*CommentMessageResult
	var count int
	DB.Model(&Message{}).Where("type=3 AND `to`=?", userId).Count(&count)
	paginate := &util.Paginate{Page: page, Limit: limit, Count: count}
	if count <= 0 {
		return result, paginate, nil
	}
	err := DB.Table("media_message m").Select("m.id, a.id article_id,a.title, c.content,u.wechat_name name,m.is_read, m.created_at,u.head_portrait").Joins("left join comments c on m.target=c.id left join articles a on a.id=c.a_id left join user_detail u on u.user_id=c.user_id").Where("m.type=3 AND m.`to`=?", userId).Order("m.created_at desc").Offset(paginate.Offset()).Limit(paginate.Limit).Scan(&result).Error
	if err != nil {
		return nil, nil, err
	}
	var ids []int
	for _, i := range result{
		ids = append(ids, i.ID)
	}
	readMessage(ids)
	return result, paginate, nil
}

func readMessage(ids []int) {
	DB.Table("media_message").Where("id in (?)", ids).Where("is_read=0").Update("is_read", 1)
}
/**
	获取关注消息
 */
func GetFollowMessageList(userId int, page int, limit int) ([]*FollowMessageResult, *util.Paginate, error) {
	var result []*FollowMessageResult
	var count int
	DB.Model(&Message{}).Where("type=4 AND `to`=?", userId).Count(&count)
	paginate := &util.Paginate{Page: page, Limit: limit, Count: count}
	if count <= 0 {
		return result, paginate, nil
	}
	err := DB.Model(&Message{}).Select("media_message.id,user_detail.wechat_name name,user_detail.head_portrait,media_message.is_read,media_message.created_at").Joins("left join user_detail on user_detail.user_id=media_message.`from`").Order("media_message.created_at desc").Where("type=4 AND `to`=?", userId).Offset(paginate.Offset()).Limit(paginate.Limit).Scan(&result).Error
	if err != nil {
		return nil, nil, err
	}
	var ids []int
	for _, i := range result{
		ids = append(ids, i.ID)
	}
	readMessage(ids)
	return result, paginate, nil
}

/**
	获取收藏和分享文章
 */
func GetFAndSMessageList(userId int, page int, limit int, t int) ([]*FAndSMessageResult, *util.Paginate, error) {
	var result []*FAndSMessageResult
	var count int
	DB.Model(&Message{}).Where("type=? AND `to`=?", t, userId).Count(&count)
	paginate := &util.Paginate{Page: page, Limit: limit, Count: count}
	if count <= 0 {
		return result, paginate, nil
	}
	err := DB.Model(&Message{}).Select("media_message.id,user_detail.wechat_name name,user_detail.head_portrait,media_message.is_read,media_message.created_at,articles.title").Joins("left join user_detail on user_detail.user_id=media_message.`from` left join articles on articles.id=media_message.target").Order("media_message.created_at desc").Where("type=? AND `to`=?", t, userId).Offset(paginate.Offset()).Limit(paginate.Limit).Scan(&result).Error
	if err != nil {
		return nil, nil, err
	}
	var ids []int
	for _, i := range result{
		ids = append(ids, i.ID)
	}
	readMessage(ids)
	return result, paginate, nil
}
type NoticeMessageContent struct {
	CreatedAt time.Time `json:"created_at"`
	Title string `json:"title"`
	Content string `json:"content"`
}

func NoticeContent(id int) *NoticeMessageContent{
	var result NoticeMessageContent
	DB.Model(&Message{}).Select("media_message.created_at,mc.title,mc.content").Joins("left join media_message_content mc on mc.msg_id=media_message.id").Where("media_message.id=? AND (type=0 OR type=1)", id).Scan(&result)
	return &result
}

/**
	获取通知
 */
func GetNotice() ([]*MessageResult, error) {
	var result []*MessageResult
	err := DB.Model(&Message{}).Select("media_message.id, mc.title, is_read, media_message.created_at").Joins("left join media_message_content mc on mc.msg_id=media_message.id").Where("media_message.`type`=0 AND media_message.`to`=0").Order("media_message.created_at desc").Scan(&result).Error
	if err != nil {
		return nil, err
	}
	return result, nil
}